#!/usr/bin/env python2

import os
import errno
import re
import ConfigParser
import json
import socket
import time
import mmap
import shutil
import sys

from config import Config
from utils import Exp, _dmsg, _dwarn, _derror, _human_readable, _human_unreadable, _exec_pipe, _exec_pipe1, _exec_system, \
        _str2dict, _syserror, _syswarn


DEBUG = False

class PoolManage(object):
    def __init__(self, config):
        self.config = config
        self.home = os.path.join(self.config.home, 'data/disk/pool')

    def pool_list(self):
        if DEBUG:
            return []
        res = _exec_pipe([self.config.admin, '--poolist'], 0, False)[:-1]
        return res.split()

    def pool_create(self, pool):
        if DEBUG:
            return
        res = _exec_pipe([self.config.admin, '--poolcreate', pool], 0, False)[:-1]

    def pool_remove(self, pool):
        if DEBUG:
            return
        res = _exec_pipe([self.config.admin, '--poolremove', pool], 0, False)[:-1]

    def pool_cleanup(self, pool):
        if DEBUG:
            return
        res = _exec_pipe([self.config.admin, '--pooldrop', pool], 0, False)[:-1]

    def __get_repnum(self, pool):
        res = _exec_pipe([self.config.lichbd, "attr", "get", pool, "lich_system_repnum"], 0, False)[:-1]
        return (int)(res.strip().split('/')[0])

    def __try_dispatch(self, pool, repnum=False, retry=0, timeout=20):
        if not repnum:
            repnum = self.__get_repnum(pool)
        res = _exec_pipe1([self.config.inspect, "--dispatch", pool, "", str(repnum)], retry, False, timeout)

    def __try_find(self, pool, retry=0, timeout=20):
        res = _exec_pipe1([self.config.lichbd, "find", "/" + pool], retry, False, timeout)

    def __etcd_get_status(self, pool):
        cmd = ["etcdctl", "get", os.path.join("/lich4/poolstatus", pool)]
        try:
            s, e = _exec_pipe1(cmd, retry=1, p=False)
        except Exp, e:
            return "Unavailable"
        return s

    def status(self, pool):
        '''
        try:
            self.__try_find(pool, retry=_retry, timeout=_timeout / 2)
        except Exp, e:
            #_dwarn("StoragePool %s find fail errno:%d" % (pool, e.errno))
            return 'Unavailable'

        try:
            self.__try_dispatch(pool, retry=_retry, timeout=_timeout / 2)
        except Exp, e:
            #_dwarn("StoragePool %s dispatch fail errno:%d" % (pool, e.errno))
            return "Readonly" if e.errno == errno.ENOSPC else "Unavailable"

        return "Available"
        '''
        return self.__etcd_get_status(pool)


if __name__ == '__main__':
    pm = PoolManage(Config())
    poolist = pm.pool_list()
    for pool in poolist:
        print pm.status(pool)
